package model;

import excepetion.NoEnoughPapersException;
import paper.Paper;
import stategy.PaperSelectionStrategy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class PaperList {
    private final List<Paper> papers = new ArrayList<>();
    private PaperSelectionStrategy strategy;

    public void addPaper(Paper p) {
        papers.add(p);
    }

    public List<Paper> getAllPapers() {
        return Collections.unmodifiableList(papers);
    }

    public void setStrategy(PaperSelectionStrategy strategy) {
        this.strategy = strategy;
    }

    public List<Paper> selectPaperByStrategy(Student student) throws NoEnoughPapersException {
        if (student.hasSelected()) return null;

        List<Paper> available = papers.stream()
                .filter(p -> p.getType().equals(student.getPreferenceType()))
                .filter(p -> !p.getTitle().contains("[已选]"))
                .collect(Collectors.toList());

        if (available.size() < student.getQuantity()) {
            throw new NoEnoughPapersException(student.getName(), student.getQuantity(), available.size());
        }

        List<Paper> selected = strategy.select(available, student.getQuantity());

        for (Paper p : selected) {
            papers.remove(p);
            papers.add(new MarkedPaper(p.getTitle() + " [已选]", p.getType()));
        }

        student.setSelected(true);
        return selected;
    }

    // 内部使用标记类防止被重复选择
    static class MarkedPaper extends Paper {
        private final String type;

        public MarkedPaper(String title, String type) {
            super(title);
            this.type = type;
        }

        @Override
        public String getType() {
            return type;
        }
    }
}
